package org.example.system.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.exception.ServiceException;
import org.example.system.entity.StudentEntity;
import org.example.system.mapper.StudentMapper;
import org.example.system.service.StudentService;
import org.example.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 学生服务实现
 */
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 学生登录
     *
     * @param student
     * @return
     */
    @Override
    public String login(StudentEntity student) {
        // 生成token（JwtUtil）
        String key = student.getId() + "," + student.getNumber() + "," + UUID.randomUUID().toString();
        String token = JwtUtil.createToken(key);
        // 把token放入redis缓存
        redisTemplate.opsForValue().set("LOGIN_STUDENT_TOKEN:" + key, token, 30, TimeUnit.MINUTES);
        // 返回token
        return token;
    }

    /**
     * 按条件分页查询
     *
     * @param student
     * @return
     */
    @Override
    public IPage<StudentEntity> selectPage(StudentEntity student) {
        LambdaQueryWrapper<StudentEntity> wrapper = new LambdaQueryWrapper<>();
        // 条件
        if (StrUtil.isNotEmpty(student.getUsername())) {
            wrapper.like(StudentEntity::getUsername, student.getUsername());    // 相似的姓名（模糊查询）
        }
        if (StrUtil.isNotEmpty(student.getNumber())) {
            wrapper.eq(StudentEntity::getNumber, student.getNumber());    // 相同的学号（精确查询）
        }
        if (StrUtil.isNotEmpty(student.getMajor())) {
            wrapper.like(StudentEntity::getMajor, student.getMajor());    // 相似的专业班级（模糊查询）
        }
        if (StrUtil.isNotEmpty(student.getSex())) {
            wrapper.eq(StudentEntity::getSex, student.getSex());    // 相同的性别（精确查询）
        }
        if (student.getBirthday() != null) {
            wrapper.eq(StudentEntity::getBirthday, student.getBirthday());    // 相同的生日（精确查询）
        }
        if (StrUtil.isNotEmpty(student.getMobile())) {
            wrapper.like(StudentEntity::getMobile, student.getMobile());    // 相似的联系电话（模糊查询）
        }
        if (StrUtil.isNotEmpty(student.getAddress())) {
            wrapper.like(StudentEntity::getAddress, student.getAddress());    // 相似的家庭住址（模糊查询）
        }
        if (StrUtil.isNotEmpty(student.getEnable())) {
            wrapper.eq(StudentEntity::getEnable, student.getEnable());    // 相同的启用状态（精确查询）
        }
        IPage<StudentEntity> page = new Page<>();
        page.setCurrent(student.getPageNum());
        page.setSize(student.getPageSize());
        return studentMapper.selectPage(page, wrapper);
    }

    /**
     * 添加学生
     *
     * @param student
     * @return
     */
    @Override
    public int add(StudentEntity student) {
        // 用相同的学号去查数据库
        LambdaQueryWrapper<StudentEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentEntity::getNumber, student.getNumber());   // 相同的学号
        List<StudentEntity> existList = studentMapper.selectList(wrapper);
        // 如果存在抛出一个自定义异常
        if (null != existList && existList.size() > 0) { // 证明存在相同的学号
            throw new ServiceException("学号已存在");
        }
        student.setPassword(DigestUtil.bcrypt(student.getPassword()));
        student.setCreateTime(new Date());
        return studentMapper.insert(student);
    }

    /**
     * 修改
     *
     * @param student
     * @return
     */
    @Override
    public int update(StudentEntity student) {
        // 用相同的学号去查数据库
        LambdaQueryWrapper<StudentEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentEntity::getNumber, student.getNumber());
        List<StudentEntity> existList = studentMapper.selectList(wrapper);
        // 如果存在抛出一个自定义异常
        if (null != existList && existList.size() > 0) { // 证明存在相同的学号
            StudentEntity existStudent = existList.get(0);
            if (!existStudent.getId().equals(student.getId())) {
                throw new ServiceException("学号已存在");
            }
        }
        // 如果匹配相同则不修改密码
        if (student.getPassword().equals(existList.get(0).getPassword()) && student.getPassword() != null) {
            student.setPassword(null);
        } else {
            student.setPassword(DigestUtil.bcrypt(student.getPassword()));
        }
        student.setUpdateTime(new Date());
        return studentMapper.updateById(student);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(Long[] ids) {
        return studentMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 根据id获取信息
     *
     * @param id
     * @return
     */
    @Override
    public StudentEntity getOne(Long id) {
        return studentMapper.selectById(id);
    }

    /**
     * 根据学号获取信息
     *
     * @param number
     * @return
     */
    @Override
    public StudentEntity getOneBySId(String number) {
        // 用相同的学号去查数据库
        LambdaQueryWrapper<StudentEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentEntity::getNumber, number);
        List<StudentEntity> existList = studentMapper.selectList(wrapper);
        if (existList != null && existList.size() > 0) {
            return existList.get(0);
        }
        return null;
    }
}
